package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    protected CosManager cosManager;

    @Resource
    protected CosClientConfig cosClientConfig;

    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix){
        //校验图片
        validPicture(inputSource);
        //图片上传地址
        String uuid= RandomUtil.randomString(16);
        String originFilename=getOriginalFilename(inputSource);
        String uploadFilename=String.format("%s_%s.%s", DateUtil.formatDate(new Date()),  uuid, FileUtil.getSuffix(originFilename));
        String uploadPath=String.format("/%s/%s",uploadPathPrefix,uploadFilename);
        //创建临时文件
        File file=null;
        try {
            file=File.createTempFile(uploadPath,null);
            processFile(inputSource,file);
            //上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                CIObject compressCiObject = objectList.get(0);
                CIObject thumbnailCiObject=compressCiObject;
                if(objectList.size()>1){
                     thumbnailCiObject = objectList.get(1);
                }

                //封装压缩图返回结果
                return buildResult(originFilename, compressCiObject,thumbnailCiObject,imageInfo);
            }

            // 5. 封装返回结果
            return buildResult(originFilename, file, uploadPath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            this.deleteTempFile(file);
        }

    }

    private UploadPictureResult buildResult(String originFilename, CIObject compressCiObject, CIObject thumbnailCiObject,ImageInfo imageInfo) {
        int picWidth=compressCiObject.getWidth();
        int picHeight=compressCiObject.getHeight();
        double picScale= NumberUtil.round(picWidth*1.0/picHeight,2).doubleValue();
        //封装返回结果
        UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                .picName(FileUtil.mainName(originFilename))
                .picWidth(picWidth)
                .picHeight(picHeight)
                .picScale(picScale)
                .picColor(imageInfo.getAve())
                .picFormat(compressCiObject.getFormat())
                .picSize((compressCiObject.getSize().longValue()))
                .url(cosClientConfig.getHost() + "/" + compressCiObject.getKey())
                .thumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey())
                .build();
        return uploadPictureResult;
    }


    protected abstract void processFile(Object inputSource, File file);

    protected abstract String getOriginalFilename(Object inputSource);

    protected abstract void validPicture(Object inputSource);

    //删除临时文件
    protected  void deleteTempFile(File file){
        if(file!=null){
            return;
        }
        //删除
        boolean delete = file.delete();
        if(!delete){
            log.error("file delete error,file={}",file.getAbsolutePath());
        }
    }

    // 封装返回结果
    protected  UploadPictureResult buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo){
        int picWidth=imageInfo.getWidth();
        int picHeight=imageInfo.getHeight();
        double picScale= NumberUtil.round(picWidth*1.0/picHeight,2).doubleValue();
        //封装返回结果
        UploadPictureResult uploadPictureResult = UploadPictureResult.builder()
                .picName(FileUtil.mainName(originFilename))
                .picWidth(picWidth)
                .picHeight(picHeight)
                .picScale(picScale)
                .picColor(imageInfo.getAve())
                .picFormat(imageInfo.getFormat())
                .picSize(FileUtil.size(file))
                .url(cosClientConfig.getHost() + "/" + uploadPath)
                .build();
        return uploadPictureResult;
    }



}
